import random
import json
import re
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from django import http

from users.models import User
from ihome_01.libs.captcha.captcha import captcha
from ihome_01.libs.yuntongxun.sms import CCP
from ihome_01.utils import constants
from ihome_01.utils.response import RET


class ImageCodeView(View):
    """图形验证码"""
    def get(self,request):
        cur = request.GET.get("cur")  # 验证码编号
        # pre = request.GET.get("pre")  # 上一次验证码编号

        # 生成图片验证码
        _, text, image = captcha.generate_captcha()
        print("image:%s"%text)

        # 2, 存储图片验证码的值到redis中
        redis_conn = get_redis_connection("code")
        redis_conn.set("image_code_%s"%cur,text,constants.IMAGE_VALIDITY_TIME)

        # 3, 返回图片
        return http.HttpResponse(image, content_type="image/png")


class SMSView(View):
    """短信验证码"""
    def post(self,request):
        # 1. 获取参数
        data_dict = json.loads(request.body.decode())
        mobile = data_dict.get("mobile")
        text = data_dict.get("text")
        cur = data_dict.get("id")

        # 2.校验参数
        # 2.0 设置管道
        redis_conn = get_redis_connection("code")
        pipeline = redis_conn.pipeline()
        # 2,1 判断标记是否过期
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            return http.JsonResponse({"errno": RET.REQERR, "errmsg": "短信频繁发送"})

        # 2.2 为空检验
        if not all([mobile,text,cur]):
            return http.JsonResponse({"errno": RET.NECESSARYPARAMERR,"errmsg": "参数不全"})

        # 2,3 手机号格式
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({"errno": RET.MOBILEERR, "errmsg": "手机号格式有误"})

        # 2,4 校验手机号是否重复
        count = User.objects.filter(mobile=mobile).count()
        if count != 0:
            return http.JsonResponse({"erron": RET.DATAEXIST,"errmsg": "该手机号已注册"})

        # 2,5 图片验证码正确性
        redis_image_code = redis_conn.get("image_code_%s" % cur)
        if not redis_image_code:
            return http.JsonResponse({"errno": RET.NODATA, "errmsg": "图片验证码已过期"})
        if text.upper() != redis_image_code.decode().upper():
            return http.JsonResponse({"errno": RET.DATAERR, "errmsg": "图片验证码错误"})

        # 3,发送短信,数据入库
        sms_code = "%06d" % random.randint(0, 999999)
        print("sms_code = %s" % sms_code)

        # # 【云通讯】您使用的是云通讯短信模板，您的验证码是 38389438，请于5分钟内正确输入 注意： 测试的短信模板编号为1
        # result = CCP().send_template_sms(mobile, [sms_code, constants.SMS_VALIDITY_TIME], 1)

        # # 使用celery发送短信
        # from celery_tasks.sms.tasks import send_message
        # result = send_message.delay(mobile, sms_code)
        #
        # # 3,1 判断是否发送成功
        # if result == -1:
        #     return http.JsonResponse({"errno": 4001, "errmsg": "短信发送失败"})

        # 3,2 保存短信验证码到redis,方便之后判断短信的正确性
        pipeline.set("sms_code_%s" % mobile, sms_code, constants.SMS_VALIDITY_TIME*60)

        # 3,3 设置标记,防止1分钟之内, 短信多次发送
        pipeline.set("send_flag_%s" % mobile, 1, constants.SMS_SENDING_INTERVAL_TIME)

        # 3,4 提交管道
        pipeline.execute()

        # 4,返回响应
        return http.JsonResponse({"errno": RET.OK,"errmsg": "发送成功"})

